package edu.ynu.se.xiecheng.achitectureclass.common.utils.test;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class TokenFetcher {

    public static String fetchToken() {
        // API URL (根据您的截图调整为实际的 URL)
        String url = "http://42.193.14.241:7000/ysapi/subAccount/getToken";

        // 请求头配置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // 请求体是 JSON 格式

        // 请求体配置
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("accountId", "1ca7f0ab24ba41b291346347ec30140e");

        // 封装请求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);

        // 解析响应
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.get("data") instanceof Map) {
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                return (String) data.get("accessToken"); // 提取 accessToken
            } else {
                throw new RuntimeException("Invalid response format");
            }
        } else {
            throw new RuntimeException("Failed to fetch token. Status code: " + response.getStatusCode());
        }
    }

    public static void main(String[] args) {
        String token = fetchToken();
        System.out.println("Access Token: " + token);
    }
}
